package com.xzm.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class TestZookeeper {
    //主机加端口，主机与主机之间用逗号隔开。
    private static String connectString =
            "47.102.155.48:2181,47.102.155.48:2182,47.102.155.48:2183";
    private static int sessionTimeout = 2000;
    private ZooKeeper zkClient = null;
    @Before
    @Test
    public void init() throws Exception {
        zkClient = new ZooKeeper(connectString, sessionTimeout,
                new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        // 收到事件通知后的回调函数（用户的业务逻辑）
                        List<String> children = null;
                        try {
                            children = zkClient.getChildren("/",
                                    true);
                            for (String child : children) {
                                System.out.println(child);
                            }
                        } catch (KeeperException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
        });
    }

    // 创建子节点
    @Test
    public void create() throws Exception {
        // 参数 1：要创建的节点的路径； 参数 2：节点数据 ； 参数 3：节点权限 ；参数 4：节点的类型
        String nodeCreated = zkClient.create("/hfut",
                "huangdongdong".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
    }

    // 获取子节点
    @Test
    public void getChildren() throws Exception {
        List<String> children = zkClient.getChildren("/",
                true);
        for (String child : children) {
            System.out.println(child);
        }
        //设置为true，此时监听根节点"/"是否有变化，有的话，调用上process函数。
        // 延时阻塞
        Thread.sleep(Long.MAX_VALUE);
    }

    // 判断 znode 是否存在
    @Test
    public void exist() throws Exception {
        Stat stat = zkClient.exists("/eclipse", false);
        System.out.println(stat == null ? "not exist" : "exist");
    }
}
